Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added tests for JobManager #263

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Added tests for JobManager #263

wants to merge 1 commit into from

Conversation

dwang3851
Copy link

  • Added test cases for JobManager
  • Made slight changes to imports in tango.py to prevent circular import issues

@dwang3851 dwang3851 requested review from a team and 20wildmanj and removed request for a team November 10, 2024 18:33
Copy link

coderabbitai bot commented Nov 10, 2024

📝 Walkthrough

Walkthrough

The changes introduce a new file, tests/testJobManager.py, which contains a suite of unit tests for the JobManager class. The tests are structured using the unittest framework and cover various functionalities of the JobManager, including job management and error handling. The setup includes initializing a testing environment and creating mock jobs to simulate interactions with the job queue.

Changes

File Change Summary
tests/testJobManager.py Added a new test class TestJobManager with unit tests for JobManager, including methods for starting the manager, generating job IDs, and handling job assignments and failures.

Sequence Diagram(s)

sequenceDiagram
    participant TM as Test Manager
    participant JM as Job Manager
    participant JQ as Job Queue
    participant W as Worker

    TM->>JM: test_start()
    JM->>JM: set running = True
    TM->>JM: test__getNextID()
    JM->>JM: generate next job ID
    TM->>JM: test_manage_worker_works()
    JM->>JQ: assign job
    JQ->>W: start job
    W->>JM: job assigned successfully
    TM->>JM: test_manage_worker_fails()
    JM->>W: simulate job failure
    W->>JM: job failed
    JM->>JM: call makeDead()
Loading

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
tests/testJobManager.py (2)

25-76: Consider improving setUp documentation and error handling.

The setUp method handles multiple VMMS configurations but could benefit from:

  1. Docstring explaining the setup process
  2. Better error handling for unsupported VMMS_NAME

Consider adding a docstring and improving error handling:

     def setUp(self):
+        """Initialize test environment with appropriate VMMS configuration.
+        
+        Cleans Redis if enabled and sets up the appropriate Virtual Machine
+        Management System (VMMS) based on Config.VMMS_NAME.
+        """
         if Config.USE_REDIS:
             __db = redis.StrictRedis(Config.REDIS_HOSTNAME, Config.REDIS_PORT, db=0)
             __db.flushall()
 
         if Config.VMMS_NAME == "ec2SSH":
             from vmms.ec2SSH import Ec2SSH
             vmms = Ec2SSH()
             self.preallocator = Preallocator({"ec2SSH": vmms})
         elif Config.VMMS_NAME == "localDocker":
             from vmms.localDocker import LocalDocker
             vmms = LocalDocker()
             self.preallocator = Preallocator({"localDocker": vmms})
         elif Config.VMMS_NAME == "distDocker":
             from vmms.distDocker import DistDocker
             vmms = DistDocker()
             self.preallocator = Preallocator({"distDocker": vmms})
         else:
-            vmms = None
-            self.preallocator = Preallocator({"default": vmms})
+            raise ValueError(f"Unsupported VMMS_NAME: {Config.VMMS_NAME}")
🧰 Tools
🪛 Ruff

35-35: Preallocator may be undefined, or defined from star imports

(F405)


41-41: Preallocator may be undefined, or defined from star imports

(F405)


47-47: Preallocator may be undefined, or defined from star imports

(F405)


50-50: Preallocator may be undefined, or defined from star imports

(F405)


77-80: Add assertions for JobManager state.

The test_start method could be more comprehensive by verifying additional JobManager state.

Consider adding more assertions:

     def test_start(self):
         self.jobManager.start()
         self.assertTrue(self.jobManager.running)
+        self.assertIsNotNone(self.jobManager.vmms)
+        self.assertEqual(self.jobManager.nextId, 1)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 92ae12f and 840c3eb.

📒 Files selected for processing (1)
  • tests/testJobManager.py (1 hunks)
🧰 Additional context used
🪛 Ruff
tests/testJobManager.py

9-9: from preallocator import * used; unable to detect undefined names

(F403)


13-13: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)


35-35: Preallocator may be undefined, or defined from star imports

(F405)


41-41: Preallocator may be undefined, or defined from star imports

(F405)


47-47: Preallocator may be undefined, or defined from star imports

(F405)


50-50: Preallocator may be undefined, or defined from star imports

(F405)


90-90: time may be undefined, or defined from star imports

(F405)


110-110: time may be undefined, or defined from star imports

(F405)


115-115: time may be undefined, or defined from star imports

(F405)


137-137: time may be undefined, or defined from star imports

(F405)

Comment on lines +88 to +112
def test_manage_worker_works(self):
def mock_getNextPendingJob():
time.sleep(0.2)
self.job1.setId(1)
return self.job1

def mock_reuseVM(job):
job.assigned = True
job.vm = self.vm
self.preallocator.vmms[job.vm.vmms] = self.jobManager.vmms
return self.vm

def mock_worker_init(job, vmms, jobQueue, preallocator, preVM):
pass

self.jobQueue.assignJob = MagicMock()
with patch(
"jobQueue.JobQueue.getNextPendingJob", side_effect=mock_getNextPendingJob
), patch("jobQueue.JobQueue.reuseVM", side_effect=mock_reuseVM), patch(
"worker.Worker.__init__", side_effect=mock_worker_init
):
self.jobManager.start()
time.sleep(2)
self.jobQueue.assignJob.assert_called()

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve reliability of worker tests.

The worker tests have several potential issues:

  1. Hard-coded sleep times can make tests flaky
  2. Missing cleanup in tearDown
  3. Limited assertion coverage

Consider these improvements:

  1. Use event-based synchronization instead of sleep
  2. Add proper cleanup
  3. Add more assertions for job state

Example implementation:

def test_manage_worker_works(self):
    job_ready = threading.Event()
    
    def mock_getNextPendingJob():
        job_ready.wait(timeout=1)  # More reliable than sleep
        self.job1.setId(1)
        return self.job1

    # ... rest of the test ...
    
    self.jobManager.start()
    job_ready.set()  # Signal that job is ready
    self.jobQueue.assignJob.assert_called_with(self.job1)
    self.assertTrue(self.job1.assigned)
    self.assertEqual(self.job1.vm, self.vm)

Would you like me to provide a complete implementation with these improvements?

Also applies to: 113-139

🧰 Tools
🪛 Ruff

90-90: time may be undefined, or defined from star imports

(F405)


110-110: time may be undefined, or defined from star imports

(F405)

Comment on lines +1 to +142
elif Config.VMMS_NAME == "distDocker":
from vmms.distDocker import DistDocker

vmms = DistDocker()
self.preallocator = Preallocator({"distDocker": vmms})
else:
vmms = None
self.preallocator = Preallocator({"default": vmms})

self.job1 = TangoJob(
name="sample_job_1",
vm="ilter.img",
outputFile="sample_job_1_output",
input=[],
timeout=30,
notifyURL="notifyMeUrl",
maxOutputFileSize=4096,
)

self.job2 = TangoJob(
name="sample_job_2",
vm="ilter.img",
outputFile="sample_job_2_output",
input=[],
timeout=30,
notifyURL="notifyMeUrl",
maxOutputFileSize=4096,
)

self.jobQueue = JobQueue(self.preallocator)
self.jobQueue.reset()
self.jobManager = JobManager(self.jobQueue)
self.vm = self.createTangoMachine(image="autograding_image", vmms=vmms)

def test_start(self):
self.jobManager.start()
self.assertTrue(self.jobManager.running)

def test__getNextID(self):
init_id = self.jobManager.nextId
for i in range(1, Config.MAX_JOBID + 100):
id = self.jobManager._getNextID()
self.assertEqual(init_id + i - 1, id)
self.jobManager.nextId = init_id

def test_manage_worker_works(self):
def mock_getNextPendingJob():
time.sleep(0.2)
self.job1.setId(1)
return self.job1

def mock_reuseVM(job):
job.assigned = True
job.vm = self.vm
self.preallocator.vmms[job.vm.vmms] = self.jobManager.vmms
return self.vm

def mock_worker_init(job, vmms, jobQueue, preallocator, preVM):
pass

self.jobQueue.assignJob = MagicMock()
with patch(
"jobQueue.JobQueue.getNextPendingJob", side_effect=mock_getNextPendingJob
), patch("jobQueue.JobQueue.reuseVM", side_effect=mock_reuseVM), patch(
"worker.Worker.__init__", side_effect=mock_worker_init
):
self.jobManager.start()
time.sleep(2)
self.jobQueue.assignJob.assert_called()

def test_manage_worker_fails(self):
def mock_getNextPendingJob():
time.sleep(2)
self.job1.setId(1)
return self.job1

def mock_reuseVM(job):
job.assigned = True
job.vm = self.vm
self.preallocator.vmms[job.vm.vmms] = self.jobManager.vmms
return self.vm

def mock_worker_init(job, vmms, jobQueue, preallocator, preVM):
raise RuntimeError("Job failed")

self.jobQueue.assignJob = MagicMock()
self.jobQueue.makeDead = MagicMock()

with patch(
"jobQueue.JobQueue.getNextPendingJob", side_effect=mock_getNextPendingJob
), patch("jobQueue.JobQueue.reuseVM", side_effect=mock_reuseVM), patch(
"worker.Worker.__init__", side_effect=mock_worker_init
):
self.jobManager.start()
time.sleep(4)
self.jobQueue.makeDead.assert_called_once()


if __name__ == "__main__":
unittest.main()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add missing test cases for comprehensive coverage.

The current test suite is missing several important test cases:

  1. Error handling for invalid job configurations
  2. Concurrent job processing
  3. Job timeout scenarios
  4. Resource cleanup

Would you like me to help generate additional test cases to improve coverage?

🧰 Tools
🪛 Ruff

9-9: from preallocator import * used; unable to detect undefined names

(F403)


13-13: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)


35-35: Preallocator may be undefined, or defined from star imports

(F405)


41-41: Preallocator may be undefined, or defined from star imports

(F405)


47-47: Preallocator may be undefined, or defined from star imports

(F405)


50-50: Preallocator may be undefined, or defined from star imports

(F405)


90-90: time may be undefined, or defined from star imports

(F405)


110-110: time may be undefined, or defined from star imports

(F405)


115-115: time may be undefined, or defined from star imports

(F405)


137-137: time may be undefined, or defined from star imports

(F405)

Comment on lines +1 to +10
import unittest
import redis
from mock import MagicMock, patch

from jobManager import JobManager
from jobQueue import JobQueue
from tangoObjects import TangoJob, TangoMachine
from config import Config
from preallocator import *

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Fix import statements for better maintainability and reliability.

  1. Replace the wildcard import with explicit imports from preallocator
  2. Add missing time module import which is used in test methods

Apply this diff:

 import unittest
 import redis
+ import time
 from mock import MagicMock, patch

 from jobManager import JobManager
 from jobQueue import JobQueue
 from tangoObjects import TangoJob, TangoMachine
 from config import Config
-from preallocator import *
+from preallocator import Preallocator
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import unittest
import redis
from mock import MagicMock, patch
from jobManager import JobManager
from jobQueue import JobQueue
from tangoObjects import TangoJob, TangoMachine
from config import Config
from preallocator import *
import unittest
import redis
import time
from mock import MagicMock, patch
from jobManager import JobManager
from jobQueue import JobQueue
from tangoObjects import TangoJob, TangoMachine
from config import Config
from preallocator import Preallocator
🧰 Tools
🪛 Ruff

9-9: from preallocator import * used; unable to detect undefined names

(F403)

Comment on lines +13 to +24
def createTangoMachine(self, image, vmms, vmObj={"cores": 1, "memory": 512}):
"""createTangoMachine - Creates a tango machine object from image"""
return TangoMachine(
name=image,
vmms=vmms,
image="%s" % (image),
cores=vmObj["cores"],
memory=vmObj["memory"],
disk=None,
network=None,
)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Fix mutable default argument in createTangoMachine method.

Using mutable default arguments in Python can lead to unexpected behavior if the default value is modified.

Apply this diff:

-    def createTangoMachine(self, image, vmms, vmObj={"cores": 1, "memory": 512}):
+    def createTangoMachine(self, image, vmms, vmObj=None):
         """createTangoMachine - Creates a tango machine object from image"""
+        if vmObj is None:
+            vmObj = {"cores": 1, "memory": 512}
         return TangoMachine(
             name=image,
             vmms=vmms,
             image="%s" % (image),
             cores=vmObj["cores"],
             memory=vmObj["memory"],
             disk=None,
             network=None,
         )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def createTangoMachine(self, image, vmms, vmObj={"cores": 1, "memory": 512}):
"""createTangoMachine - Creates a tango machine object from image"""
return TangoMachine(
name=image,
vmms=vmms,
image="%s" % (image),
cores=vmObj["cores"],
memory=vmObj["memory"],
disk=None,
network=None,
)
def createTangoMachine(self, image, vmms, vmObj=None):
"""createTangoMachine - Creates a tango machine object from image"""
if vmObj is None:
vmObj = {"cores": 1, "memory": 512}
return TangoMachine(
name=image,
vmms=vmms,
image="%s" % (image),
cores=vmObj["cores"],
memory=vmObj["memory"],
disk=None,
network=None,
)
🧰 Tools
🪛 Ruff

13-13: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant